package com.yupi.springbootinit.controller;


import cn.hutool.json.JSONUtil;
import com.yupi.springbootinit.config.ThreadPoolExecutorConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 线程池测试
 */
@RestController
@RequestMapping("/queue")
@Slf4j
public class QueueController {
    // 注入线程池实例
    @Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @GetMapping("/addTask")
    public void addTask(String task){
        CompletableFuture.runAsync(()->{
            log.info("任务执行中" + task + "执行人：" +Thread.currentThread().getName());
            try {
                Thread.sleep(20000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },  threadPoolExecutor);
    }

    @GetMapping("/get")
    public String getThreadPoolArgs(){
        HashMap<String, Object> map = new HashMap<>();
        map.put("线程池队列长度", threadPoolExecutor.getQueue().size());
        map.put("任务总数",threadPoolExecutor.getTaskCount());
        map.put("已完成任务数",threadPoolExecutor.getCompletedTaskCount());
        map.put("正在工作得线程数",threadPoolExecutor.getActiveCount());
        return JSONUtil.toJsonStr(map);
    }
}
